package hgx.spring.cloud.lession.productrepertory.controller;/**
 * Created by liujun on 2018/3/26.
 */

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;

import hgx.spring.cloud.lession.productrepertory.api.ProductRepository;
import hgx.spring.cloud.lession.productrepertory.hystrix.ProductCreateHystrixCommand;
import hgx.spring.cloud.lession.productrepertory.hystrix.ProductFindAllHystrixCommand;
import hgx.spring.cloud.lession.productrepertory.hystrix.ProductGetByIdHystrixCommand;
import hgx.spring.cloud.lession.productrepertory.hystrix.ProductGetByIdHystrixObservableCommand;
import hgx.spring.cloud.lession.productrepertory.hystrix.batch.ProductGetByIdCollapseHystrixCommand;
import hgx.spring.cloud.lession.productrepertory.vo.ProductVo;
import hgx.spring.cloud.lession.productrepertory.vo.ReponseProductListVo;
import hgx.spring.cloud.lession.productrepertory.vo.ReponseProductVo;
import rx.Subscriber;

/**
 * @author Administrator
 * @create 2018-03-26 14:32
 */
@RestController
@RequestMapping("/comm/products")
public class ProductHystrixDemoController {
    private final static Logger logger = Logger.getLogger(ProductHystrixDemoController.class);

    @Autowired
    private ProductRepository productRepository;

    /**
     * 保存商品信息
     *
     * @param productVo
     * @return
     */
    @PostMapping("/save")
    public ReponseProductVo saveProduct(@RequestBody ProductVo productVo) {

        ProductCreateHystrixCommand command = new ProductCreateHystrixCommand(productRepository,productVo);
        System.out.println("1: ----------------");
        long startTime = System.currentTimeMillis();
        Future<ReponseProductVo> future = command.queue();
        System.out.println("2: ----------------command.queue() ");
        ReponseProductVo reponse = null;
        try {
            reponse = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("5: ---------------- 耗时： " + (System.currentTimeMillis() - startTime));

        return reponse;
    }

    /**
     * 查询所有商品信息
     *
     * @return
     */
    @GetMapping("")
    public ReponseProductListVo findAll() {

        ProductFindAllHystrixCommand command = new ProductFindAllHystrixCommand(productRepository);
        System.out.println("1: ----------------");
        long startTime = System.currentTimeMillis();
        Future<ReponseProductListVo> future = command.queue();
        System.out.println("2: ----------------command.queue() ");
        ReponseProductListVo reponse = null;
        try {
            reponse = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("5: ---------------- 耗时： " + (System.currentTimeMillis() - startTime));

        return reponse;
    }

    /**
     * 根据商品ID 查询商品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ReponseProductVo getProductById(@PathVariable("id") Long id) {

        ProductGetByIdHystrixCommand command = new ProductGetByIdHystrixCommand(productRepository,id);
        System.out.println("\r\n");
        System.out.println("1: ----------------");
        long startTime = System.currentTimeMillis();
        Future<ReponseProductVo> future = command.queue();
        System.out.println("2.1: ----------------command.queue() ");
        ReponseProductVo reponse = null;
        try {
            reponse = future.get();
        } catch (InterruptedException e) {
            System.err.println("2.2:  "+e);
        } catch (ExecutionException e) {
            System.err.println("2.3: "+e);
        }
        System.out.println("5: ---------------- 耗时： " + (System.currentTimeMillis() - startTime));

        return reponse;
    }

    /**
     * 根据商品ID 查询商品信息,合并请求处理
     *
     * @param id
     * @return
     */
    @GetMapping("/coll/{id}")
    public ReponseProductVo getProductByIdCollapse(@PathVariable("id") Long id) {

        ProductGetByIdCollapseHystrixCommand command = new ProductGetByIdCollapseHystrixCommand(productRepository,id);
        System.out.println("\r\n");
        System.out.println("1: ----------------");
        long startTime = System.currentTimeMillis();
        Future<ReponseProductVo> future = command.queue();
        System.out.println("2.1: ----------------command.queue() ");
        ReponseProductVo reponse = null;
        try {
            reponse = future.get();
        } catch (InterruptedException e) {
            System.err.println("2.2:  "+e);
        } catch (ExecutionException e) {
            System.err.println("2.3: "+e);
        }
        System.out.println("5: ---------------- 耗时： " + (System.currentTimeMillis() - startTime));

        return reponse;
    }

    /**
     * 根据商品ID 查询商品信息 ，Observable
     *
     * @param id
     * @return
     */
    @GetMapping("/obs/{id}")
    public ReponseProductVo getProductByIdObservable(@PathVariable("id") Long id) {

        final ReponseProductVo[] reponse = {null};
        ProductGetByIdHystrixObservableCommand command = new ProductGetByIdHystrixObservableCommand(productRepository,id);
        System.out.println("\r\n");
        System.out.println("1: ----------------");
        long startTime = System.currentTimeMillis();
        rx.Observable<ReponseProductVo> observable= command.toObservable();

        Subscriber<ReponseProductVo> subscriber=new Subscriber<ReponseProductVo>() {
            @Override
            public void onCompleted() {
                System.out.println("******* onCompleted ");
            }

            @Override
            public void onError(Throwable e) {

                System.out.println("~~~~~ error: "+e.getMessage());
            }

            @Override
            public void onNext(ReponseProductVo reponseProductVo) {
                System.out.println("======= flag: "+reponseProductVo.getMsg());
                reponse[0] =reponseProductVo;
            }
        };

//        subscriber.unsubscribe();
        System.out.println("2.1 ------- call observable.subscribe(subscriber) ");
        observable.subscribe(subscriber); // 观察者注册到被观察者中后，如果被观察者没有调用onCompleted() 或 onError() 方法，则会一直阻止在这里


        System.out.println("2.2: ----------------command.queue() ");


        System.out.println("5: ---------------- 耗时： " + (System.currentTimeMillis() - startTime));

        return reponse[0];
    }

    @PostMapping("/ids")
    public ReponseProductListVo getProductByIds(@RequestBody IDRequest idRequest) {
        ReponseProductListVo reponse=new ReponseProductListVo();


        return reponse;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Exception> handleException(HttpServletRequest request, Exception e) {
//        logger.error("Request FAILD, URL = {} method = {}", request.getRequestURI().toString(), request.getMethod().toString());
        logger.error(e.toString(), e);
        return new ResponseEntity<Exception>(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public static final class IDRequest {
        List<Long> ids;

        public List<Long> getIds() {
            return ids;
        }

        public void setIds(List<Long> ids) {
            this.ids = ids;
        }
    }

}
